var express = require('express');
var router = express.Router();
var axios = require('axios')
var getToken = require('../lib/getToken')

var multer = require('multer')

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/uploads')
  },
  filename: function (req, file, cb) {
    var singfileArray = file.originalname.split('.');
    var fileExtension = singfileArray[singfileArray.length - 1];
    cb(null, singfileArray[0] + '-' + Date.now() + "." + fileExtension);
    // console.log(file);
  }
})

var upload = multer({
  storage: storage
})

var image2base64 = require('image-to-base64')



var fileSystem = require('fs');
var path = require('path');
var fetch = require('node-fetch');



/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('home', { title: '人脸检测' });
});

// https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token=24.f9ba9c5341b67688ab4added8bc91dec.2592000.1485570332.282335-8574074




async function getFaceResult(imgurl, res) {
  try {
    var token = await getToken()
    var imageBase64 = await image2base64(imgurl)
 
    var faceResult = await axios.post('https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' + token, {
      image: imageBase64,
      image_type: "BASE64",
      face_field:'age,beauty,expression'
    })

    res.send({face:faceResult.data.result.face_list[0]})
  } catch (error) {
    console.log(error)
  }


}


router.post('/upload', upload.single('avatar'), async function (req, res) {
  let img = 'http://localhost:3000/uploads/' + req.file.filename
  let faceResult = await getFaceResult(img, res)

})

module.exports = router;
